import logging
import time
import warnings
from urllib.parse import quote

from tqdm import tqdm

from apps.patent.patent.spiders.account.core.patent_account_login import get_random_num, encrypt_aes_key, aes_encrypt
from apps.patent.patent.spiders.account.core.patent_user import PATENT_USER_POOL
from utils.rs_utils.rs6 import Rs6Session

warnings.filterwarnings("ignore")


def demo():

    url = "https://pss-system.cponline.cnipa.gov.cn/api/pubsearch-app-search/search/results/getResults"
    headers = {
        # "Accept": "application/json, text/plain, */*",
        # "Accept-Language": "zh-CN,zh;q=0.9,zu;q=0.8,be;q=0.7,en;q=0.6",
        "Cache-Control": "no-cache",
        "Connection": "keep-alive",
        # "Content-Type": "application/json;charset=UTF-8",
        "Origin": "https://pss-system.cponline.cnipa.gov.cn",
        "Referer": "https://pss-system.cponline.cnipa.gov.cn/retrieveList?prevPageTit=changgui",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36",
        # "language": "zh",
        # "sec-ch-ua": '"Chromium";v="134", "Not:A-Brand";v="24", "Google Chrome";v="134"',
        # "sec-ch-ua-mobile": "?0",
        # "sec-ch-ua-platform": '"Windows"',
    }
    self = Rs6Session(debug=True, proxies={})
    src_data = {
        "pagination": {"page": 1, "limit": 10},
    }
    key = get_random_num()
    headers.update(
        {
            "Accept": "application/json, text/plain, */*",
            "Content-Type": "application/json;charset=utf-8",
            "Authorization": "Bearer eyJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJuZXVzb2Z0IiwiaWF0IjoxNzQ0Njg4MTU1LCJleHAiOjE3NDQ2OTUzNTUsInVzZXJJZCI6IjE1NjA2NjcwMDE0In0.JULfCCaQB1lwtTrGdyeWpd4z2MOVtQsuvTf51g4nMjT4_6wWUoiSBzlN8AVjtxYeSh-lNfMbl8SCzhEZtrWme7lxetwcTRXDGONOml_7IxdZ0PhCMCYkDNErXHI3cNW-N2-gT0SjPssx0FFrR84ejVw9CueLHGItBvBFHCNqJxQ",
            "language": "zh",
            "EncryptAesKey": encrypt_aes_key(key),
        }
    )
    logging.basicConfig(level=logging.DEBUG)
    # print(self.request_core("https://pss-system.cponline.cnipa.gov.cn/api/userCenter/info", verify=False, method="POST", headers=headers).text)
    while True:
        user = PATENT_USER_POOL.get_user()
        key = get_random_num()
        headers.update(
            {
                "Accept": "application/json, text/plain, */*",
                # "Content-Type": "application/json;charset=utf-8",
                # "Authorization": "Bearer eyJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJuZXVzb2Z0IiwiaWF0IjoxNzQ0NzIwMDg2LCJleHAiOjE3NDQ3MjcyODYsInVzZXJJZCI6IjE1NjA2NjcwMDE0In0.UkLGvJnCS0G-hjyxu9Oo9hrz3JN482vxMGaemHh2ZPuIcvidaAm7bBzv6z0VJy-rBzYRwGu904Ow5QKk0LjUWXeUyeBBKy5Zv49o1N8MnMsmXBgDjCBOCsxbTjzlBb2ViGSUnPKlZrmI3Q6QYu8ZeMBQ9D2t_AbQNtVIu81B62Y",
                "language": "zh",
                "EncryptAesKey": encrypt_aes_key(key),
                **user.cookies,
                "content-type": "application/json",
            }
        )
        name = "华为"
        # name = '深圳微众税银信息服务有限公司'
        data = {
            **src_data,
            "executableSearchExp": quote(f"""AES({aes_encrypt(f"PA='{name}'", key)})"""),
            "parseSearchExp": quote(f"""AES({aes_encrypt(f"PA='{name}'", key)})"""),
            "searchExp": quote(f"""AES({aes_encrypt(f"申请（专利权）人=({name})", key)})"""),
            "sortFields": "-APD",
            "dbName": "CNDB,WPDB",
            "interfaceId": "2001154",
        }
        # resp = self.request_core(url=url, data=json.dumps(data, separators=(',', ':')), method="POST", headers=headers, verify=False, timeout=60)
        resp = self.request_core(url=url, json=data, method="POST", headers=headers, verify=False, timeout=60)
        if resp.status_code in [401]:
            user.set_cookies(None)
            continue
        print(resp.request.headers)
        if resp.status_code in [400]:
            self.session.cookies.clear()
            # self.session.proxies = get_company_ip_crawler_by_api()
            # print(self.session.proxies)
            for _ in tqdm(range(60)):
                time.sleep(1)
            continue
        print(resp.text[:100])
        resp = resp.json()
        if resp["status"] == 200:
            search_result_record = resp["t"]["searchResultRecord"]
            if search_result_record:
                for item in search_result_record:
                    anId = item["ap"]
                    print(anId)
                    # t_url = "https://pss-system.cponline.cnipa.gov.cn/api/pubsearch-app-tools/tools/lawstate/lawstates"
                    # data = {
                    #     "param": {
                    #         "anId": anId,
                    #     },
                    #     "pagination": {
                    #         "limit": 10,
                    #         "page": 1
                    #     },
                    #     "interfaceId": "1998376"
                    # }
                    # res = self.request_core(url=t_url, json=data, method="POST", headers=headers, verify=False)
                    # print(res.text)

            # todo 解析
            total_count = resp["t"]["pagination"]["totalCount"]
            page = resp["t"]["pagination"]["page"]
            limit = resp["t"]["pagination"]["limit"]
            src_data["pagination"]["page"] = page + 1
            if total_count <= limit * page:
                break
            # break
            # time.sleep(4)
        else:
            # time.sleep(4)
            continue

    # url = "https://pss-system.cponline.cnipa.gov.cn/api/pubsearch-app-tools/tools/lawstate/lawstates"
    # data = {
    #     "param": {
    #         "anId": "CN201611229141",
    #     },
    #     "pagination": {
    #         "limit": 10,
    #         "page": 1
    #     },
    #     "interfaceId": "1998376"
    # }
    # res = self.request(url=url, json=data, method="POST", headers=headers, verify=False)
    # print(res.text)


if __name__ == "__main__":
    demo()
